package com.dtx.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dtx.controller.in.EditUserParam;
import com.dtx.controller.in.RegisterUserParam;
import com.dtx.controller.out.UserResult;
import com.dtx.entity.User;
import com.dtx.mapper.UserMapper;
import com.dtx.msg.ResultMsg;
import com.dtx.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 杜嘟嘟
 * @since 2021-12-11
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public ResultMsg findUser(EditUserParam param) {
        Page page = new Page();
        UserResult result;
        List<UserResult> userResults = new ArrayList<>();
        List<User> list = new LambdaQueryChainWrapper<>(baseMapper).eq(param.getAge()!=null,User::getAge,param.getAge())
                .like(StringUtils.isNotEmpty(param.getName()),User::getName, param.getName())
                .like(StringUtils.isNotEmpty(param.getEmail()),User::getEmail, param.getEmail()).list();
        for (User user : list) {
            result = new UserResult();
            BeanUtil.copyProperties(user,result);
            userResults.add(result);
        }
        page.setRecords(userResults);
        return new ResultMsg(page);
    }

    @Override
    public ResultMsg saveUser(RegisterUserParam param) {
        User user = new User();
        BeanUtil.copyProperties(param,user);
        List<User> list = new LambdaQueryChainWrapper<User>(baseMapper).eq(User::getName, param.getName()).eq(User::getIsDel, 0).list();
        Assert.isTrue(list.size()==0,"用户名重复了");
        try {
            user.setIsDel(0);
            user.setCreateTime(new Date());
            user.setUpdateTime(new Date());
            userMapper.insert(user);
            return ResultMsg.success("保存成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ResultMsg.fail("保存失败");
        }

    }

    @Override
    public ResultMsg xmlFindUser(EditUserParam param) {
        Page page = new Page();
        param.setName(StringUtils.isBlank(param.getName())?null:"%"+param.getName()+"%");
        param.setEmail(StringUtils.isBlank(param.getEmail())?null:param.getEmail()+"%");
        List<UserResult> list = userMapper.xmlFindUser(param);
        return new ResultMsg(page.setRecords(list));
    }
}
